package com.asktgapp.user.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.asktgapp.JGTool.JGColor;
import com.asktgapp.JGTool.Utils;
import com.asktgapp.R;
import com.asktgapp.application.ApiUtil;
import com.asktgapp.application.Apiservice;
import com.asktgapp.application.MyApplication;
import com.asktgapp.architecture.retrofit.ApiException;
import com.asktgapp.architecture.retrofit.ApiResponseBody;
import com.asktgapp.architecture.rxjava.ExceptionHandle;
import com.asktgapp.base.BaseFragment;
import com.asktgapp.eventbus.HasNewEvent;
import com.asktgapp.hxsg.BiuEaseHelper;
import com.asktgapp.model.SystemMsgVO;
import com.asktgapp.modulebase.common.adapter.BaseAdapter;
import com.asktgapp.modulebase.common.adapter.BaseViewHolder;
import com.asktgapp.modulebase.common.util.PreferencesUtil;
import com.asktgapp.modulebase.common.util.Util;
import com.asktgapp.user.activity.FreeAskAnswerDetailActivity;
import com.asktgapp.user.activity.HomeServiceDetailActivity;
import com.asktgapp.user.activity.IndustryInfoDetailActivity;
import com.asktgapp.user.activity.QiuZuDetailActivity;
import com.asktgapp.user.activity.RentDetailActivity;
import com.asktgapp.user.activity.ServiceOrderActivity;
import com.asktgapp.user.activity.SystemPushActivity;
import com.asktgapp.user.activity.UsedMachineDetailActivity;
import com.asktgapp.widget.RefreshRecyclerView;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * time:2018/1/9
 * Create By ZhaoKai
 * Email: dczk@foxmail.com
 * Description:
 */

public class SystemMessageFragment extends BaseFragment {
    //    @InjectView(R.id.recycle)
    RefreshRecyclerView mRefreshRecyclerView;
    private RecyclerView mRecyclerView;
    private BaseAdapter mBaseAdapter;
    private int mPage = 1;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_system_message, container, false);
        ButterKnife.inject(this, viewGroup);
        return super.onCreateView(inflater, viewGroup, savedInstanceState);
    }

    @Override
    protected void initView(View rootView) {
        setHasOptionsMenu(true);
        getBaseActivity().setBackNavigationIcon();
        mRefreshRecyclerView = rootView.findViewById(R.id.recycle);
        mRefreshRecyclerView.setRefreshAction(new RefreshRecyclerView.Action() {
            @Override
            public void onAction(int page) {
                mPage = page;
                getData(mPage);
            }
        });
        mRefreshRecyclerView.setLoadMoreAction(new RefreshRecyclerView.Action() {
            @Override
            public void onAction(int page) {
                mPage = page;
                getData(mPage);
            }
        });
        mRecyclerView = mRefreshRecyclerView.getRecyclerView();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        mBaseAdapter = new BaseAdapter(getActivity()) {
            @Override
            public BaseViewHolder getViewHolder(ViewGroup parent, int viewType) {
                BaseViewHolder holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_system_message, parent, false),
                        new BaseViewHolder.Callbacks() {
                            @Override
                            public void bind(BaseViewHolder holder, Object data) {
                                FrameLayout frameLayout = holder.getView(R.id.bg);
                                TextView messgeType = holder.getView(R.id.tv_system_message_type);
                                TextView messageTime = holder.getView(R.id.tv_system_message_time);
                                TextView messageContent = holder.getView(R.id.tv_system_message_content);
                                if (data instanceof SystemMsgVO) {
                                    SystemMsgVO bean = (SystemMsgVO) data;
                                    Date date = Util.StrToDate(bean.getAdd_time(), "yyyy.MM.dd HH:mm:ss");
                                    messageTime.setText(Utils.getAskTime(date));
                                    messageContent.setText(bean.getContent());
                                    if (bean.getState() == 0) {
                                        frameLayout.setBackgroundColor(Color.WHITE);
                                    } else {
                                        frameLayout.setBackgroundColor(JGColor.MSG_BG_READ);
                                    }
                                    if (bean.getType() == 0) {
                                        messgeType.setText("问答消息");
                                    } else if (bean.getType() == 1) {
                                        messgeType.setText("关注消息");
                                    } else if (bean.getType() == 2) {
                                        messgeType.setText("系统通知");
                                        if ((!Util.isEmpty(bean.getContent())) && bean.getContent().length() > 40) {
                                            messageContent.setText(bean.getContent().substring(0, 39) + "...");
                                        }
                                    } else if (bean.getType() == 4) {
                                        messgeType.setText("咨询结束提醒");
                                    } else if (bean.getType() == 5) {
                                        messgeType.setText("新的咨询");
                                    } else if (bean.getType() == 6) {
                                        messgeType.setText("新的打分评价");
                                    } else if (bean.getType() == 7) {
                                        messgeType.setText("认证申请通知");
                                    } else if (bean.getType() == 8) {
                                        messgeType.setText("打赏消息");
                                    } else if (bean.getType() == 9 || bean.getType() == 10 || bean.getType() == 11 ||
                                            bean.getType() == 12 || bean.getType() == 13|| bean.getType() == 14) {
                                        messgeType.setText("维修常识消息");
                                    } else if (bean.getType() == 15 ) {
                                        messgeType.setText("上门服务消息");
                                    } else if (bean.getType() == 16) {
                                        messgeType.setText("意见反馈回复");
                                        if ((!Util.isEmpty(bean.getContent())) && bean.getContent().length() > 40) {
                                            messageContent.setText(bean.getContent().substring(0, 39) + "...");
                                        }
                                    }
                                }
                            }

                            @Override
                            public void onItemClick(View view, int position) {
                                final SystemMsgVO bean = (SystemMsgVO) mBaseAdapter.getData().get(position);
                                if (bean.getState() != 1) {
                                    Apiservice apiservice = ApiUtil.getInstance().create();
                                    HashMap params = new HashMap();
                                    params.put("userid", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
                                    params.put("id", bean.getId());
                                    Call<ApiResponseBody> call = apiservice.clearMsg(params);
                                    call.enqueue(new Callback<ApiResponseBody>() {
                                        @Override
                                        public void onResponse(Call<ApiResponseBody> call, Response<ApiResponseBody> response) {
                                            if (response.isSuccessful()) {
                                                bean.setState(1);
                                                mBaseAdapter.notifyDataSetChanged();
                                            } else {
                                                showTost(response.raw().message(), 1);
                                            }
                                        }

                                        @Override
                                        public void onFailure(Call<ApiResponseBody> call, Throwable t) {
                                            ApiException apiException = ExceptionHandle.handleException(t);
                                            if (apiException.isTokenInvalid()) {
                                                showUnLoginSnackbar();
                                            } else if (apiException.isNetConnected()) {
                                                showSetNetworkSnackbar();
                                            } else {
                                                showTost(apiException.getMessage(), 0);
                                            }

                                        }
                                    });
                                }
                                if (bean.getType() == 0 || bean.getType() == 1|| bean.getType() == 3
                                        || bean.getType() == 4|| bean.getType() == 5|| bean.getType() == 6) {
                                    switch (bean.getRef_type()) {
                                        //二手机
                                        case 0:
                                            Intent intent0 = new Intent(getActivity(), UsedMachineDetailActivity.class);
                                            intent0.putExtra("id", bean.getRef_id());
                                            startActivity(intent0);
                                            break;
                                        //设备出租
                                        case 1:
                                            Intent intent1 = new Intent(getActivity(), RentDetailActivity.class);
                                            intent1.putExtra("id", bean.getRef_id());
                                            startActivity(intent1);
                                            break;
                                        //设备求租
                                        case 2:
                                            Intent intent2 = new Intent(getActivity(), QiuZuDetailActivity.class);
                                            intent2.putExtra("id", bean.getRef_id());
                                            startActivity(intent2);
                                            break;
                                        //问答
                                        case 3:
                                            Intent intent = new Intent(getActivity(), FreeAskAnswerDetailActivity.class);
                                            intent.putExtra("id", bean.getRef_id());
                                            intent.putExtra("deviceId", Utils.getDeviceId(MyApplication.getInstance()));
                                            startActivity(intent);
                                            break;
                                        case 4:
//                                            if (Util.isEmpty(bean.getRef_id())) {
//                                                showTost("自己或对方不在线,请去个人中心->加入剪工->联系邮箱联系客服", 1);
//                                                return;
//                                            }
                                            if (PreferencesUtil.getBoolean(getActivity(), PreferencesUtil.KEY_IS_ENGINEER)) {
                                                BiuEaseHelper
                                                        .getInstance()
                                                        .beginSingleChat(getActivity()
                                                                , "", bean.getHuanxin_id()
                                                                , bean.getUsername()
                                                                , bean.getUser_pic(), bean.getRef_id(), 2, String.valueOf(bean.getCid()), 0);
                                            } else {
                                                BiuEaseHelper
                                                        .getInstance()
                                                        .beginSingleChat(getActivity()
                                                                , "", bean.getHuanxin_id()
                                                                , bean.getUsername()
                                                                , bean.getUser_pic(), bean.getRef_id(), 0, String.valueOf(bean.getCid()), 0);
                                            }

                                    }

                                } else if (bean.getType() == 7) {
                                    if (Util.isEmpty(bean.getRef_id())) {
                                        return;
                                    }
                                    Intent intent = new Intent(getActivity(), SystemPushActivity.class);
                                    intent.putExtra("id", bean.getRef_id());
                                    intent.putExtra("type", 1);
                                    startActivity(intent);
                                } else if (bean.getType() == 2 || bean.getType() == 8) {
                                    Intent intent = new Intent(getActivity(), SystemPushActivity.class);
                                    intent.putExtra("content", bean.getContent());
                                    intent.putExtra("type", 2);
                                    startActivity(intent);
                                } else if (bean.getType() == 9 || bean.getType() == 10 || bean.getType() == 11 ||
                                        bean.getType() == 12 || bean.getType() == 13 || bean.getType() == 14) {
                                    Intent intent = new Intent(getActivity(), IndustryInfoDetailActivity.class);
                                    intent.putExtra("id", bean.getRef_id());
                                    startActivity(intent);
//                                    showTost("现在的ID 不确定", 0);
                                } else if (bean.getType() == 15) {
                                    Intent intent = new Intent(getActivity(), HomeServiceDetailActivity.class);
                                    intent.putExtra("id",bean.getRef_id());
                                    startActivity(intent);
                                }else if(bean.getType() == 16){
                                    Intent intent = new Intent(getActivity(), SystemPushActivity.class);
                                    intent.putExtra("content", bean.getContent());
                                    intent.putExtra("type", 2);
                                    startActivity(intent);
                                }
                            }
                        });
                return holder;
            }
        };
        mRecyclerView.setAdapter(mBaseAdapter);

    }


    @Override
    public void loadData() {
//        visibleLoading();
        getData(mPage);
    }


    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.system_message, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO: 2018/1/9 标记已读操作
        clearMsg();
        return super.onOptionsItemSelected(item);
    }

    private void clearMsg() {

        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("userid", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
        showProgress(getClass().getSimpleName());
        Call<ApiResponseBody> call = apiservice.clearAllMsg(params);
        call.enqueue(new Callback<ApiResponseBody>() {
            @Override
            public void onResponse(Call<ApiResponseBody> call, Response<ApiResponseBody> response) {
                dismissProgress();
                if (response.isSuccessful()) {
                    showTost("操作成功", 0);
                    mPage = 1;
                    getData(1);
                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody> call, Throwable t) {
                dismissProgress();
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 0);
                }
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }


    public void getData(final int mPage) {
        // TODO: 2018/1/9 分页网络请求
        HashMap params = new HashMap();
        params.put("userid", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
        params.put("page", mPage);
        Apiservice apiservice = ApiUtil.getInstance().create();
        Call<ApiResponseBody<List<SystemMsgVO>>> call = apiservice.getSystemMsg(params);
        call.enqueue(new Callback<ApiResponseBody<List<SystemMsgVO>>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<List<SystemMsgVO>>> call, Response<ApiResponseBody<List<SystemMsgVO>>> response) {
                mRefreshRecyclerView.endPage();
                if (response.isSuccessful()) {
                    List<SystemMsgVO> list = response.body().getResult();
                    if (mPage == 1) {
                        if (list.size() == 0) {
                            visibleNoData();
                        } else {
                            mBaseAdapter.setData(list);
                            mRefreshRecyclerView.showNextMore(mPage);
                        }
                    } else {
                        if (list.size() == 0) {
                            mRefreshRecyclerView.showNoMore();
                        } else {
                            mBaseAdapter.addData(BaseAdapter.AddType.LASE, list);
                            mRefreshRecyclerView.showNextMore(mPage);
                        }
                    }
                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<List<SystemMsgVO>>> call, Throwable t) {
                mRefreshRecyclerView.endPage();
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 1);
                }

            }
        });


    }

    @Override
    public void onResume() {
        super.onResume();
        mPage = 1;
        getData(1);
    }
}
